import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter_demo/other/response.dart';

class HttpManager {
  static final Map _cache = <String, HttpManager>{};
  late Dio _dio;

  factory HttpManager.getInstance(String baseUrl) {
    return _cache.containsKey(baseUrl)
        ? _cache[baseUrl] : _cache[baseUrl] = HttpManager._internal(baseUrl);
  }

  HttpManager._internal(String baseUrl) {
    BaseOptions options = BaseOptions(
      baseUrl: baseUrl,
      connectTimeout: 2000,
      receiveTimeout: 2000,
    );
    _dio = Dio(options);
  }

  Future<Response> post(path, {Map<String, dynamic>? body}) async {
    print('[dio] post $path body: $body');
    Response response = await _dio.post(
        path, data: body,
        options: Options(responseType: ResponseType.plain));
    print('[dio] response ${response.data}');
    return response;
  }

  Future<Response> get(path, {Map<String, dynamic>? params}) async {
    print('[dio] get $path params: $params');
    Response response = await _dio.get(
        path, queryParameters: params,
        options: Options(responseType: ResponseType.plain));
    print('[dio] response ${response.data}');
    return response;
  }
}
